<template>
  <div class="sales-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>销售订单管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增订单
      </el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="生产中" value="producing" />
            <el-option label="待发货" value="ready" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" width="150" fixed="left" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="customerContact" label="联系人" width="120" />
        <el-table-column prop="totalAmount" label="订单金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.totalAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">{{ getPriorityText(row.priority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryDate" label="交货日期" width="120" />
        <el-table-column prop="salesperson" label="销售员" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" v-if="row.status === 'pending'">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown @command="handleCommand" v-if="row.status !== 'cancelled'">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'approve', row}" v-if="row.status === 'pending'">
                    审核通过
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'ship', row}" v-if="row.status === 'ready'">
                    确认发货
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'complete', row}" v-if="row.status === 'shipped'">
                    完成订单
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'cancel', row}" v-if="['pending', 'approved'].includes(row.status)">
                    取消订单
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="order-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-select v-model="formData.customerName" placeholder="请选择客户" filterable>
                <el-option
                  v-for="customer in customerOptions"
                  :key="customer.value"
                  :label="customer.label"
                  :value="customer.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="customerContact">
              <el-input v-model="formData.customerContact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交货日期" prop="deliveryDate">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                placeholder="请选择交货日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="formData.priority" placeholder="请选择优先级">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
                <el-option label="紧急" value="urgent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售员" prop="salesperson">
              <el-select v-model="formData.salesperson" placeholder="请选择销售员">
                <el-option
                  v-for="person in salespersonOptions"
                  :key="person.value"
                  :label="person.label"
                  :value="person.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单金额" prop="totalAmount">
              <el-input-number
                v-model="formData.totalAmount"
                :min="0"
                :precision="2"
                placeholder="请输入订单金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="订单详情" width="900px">
      <div class="order-detail" v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentOrder.customerContact }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span class="amount-text">¥{{ currentOrder.totalAmount?.toLocaleString() }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityType(currentOrder.priority)" size="small">{{ getPriorityText(currentOrder.priority) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交货日期">{{ currentOrder.deliveryDate }}</el-descriptions-item>
          <el-descriptions-item label="销售员">{{ currentOrder.salesperson }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, View, Edit, ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const currentOrder = ref(null)
const formRef = ref(null)
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerName: '',
  status: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const formData = reactive({
  id: null,
  customerName: '',
  customerContact: '',
  deliveryDate: '',
  priority: 'medium',
  salesperson: '',
  totalAmount: 0,
  remark: ''
})

// 表单验证规则
const formRules = {
  customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
  customerContact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  deliveryDate: [{ required: true, message: '请选择交货日期', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  salesperson: [{ required: true, message: '请选择销售员', trigger: 'change' }],
  totalAmount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }]
}

// 客户选项
const customerOptions = ref([
  { label: '北京科技有限公司', value: '北京科技有限公司' },
  { label: '上海贸易集团', value: '上海贸易集团' },
  { label: '深圳创新企业', value: '深圳创新企业' },
  { label: '广州制造公司', value: '广州制造公司' },
  { label: '杭州电商平台', value: '杭州电商平台' }
])

// 销售员选项
const salespersonOptions = ref([
  { label: '张三', value: '张三' },
  { label: '李四', value: '李四' },
  { label: '王五', value: '王五' },
  { label: '赵六', value: '赵六' },
  { label: '钱七', value: '钱七' }
])

// 模拟数据
const mockData = [
  {
    id: 1,
    orderNo: 'SO202401001',
    customerName: '北京科技有限公司',
    customerContact: '张经理',
    totalAmount: 125000,
    status: 'pending',
    priority: 'high',
    deliveryDate: '2024-02-15',
    salesperson: '张三',
    createTime: '2024-01-15 09:30:00',
    remark: '重要客户订单，请优先处理'
  },
  {
    id: 2,
    orderNo: 'SO202401002',
    customerName: '上海贸易集团',
    customerContact: '李总监',
    totalAmount: 89000,
    status: 'approved',
    priority: 'medium',
    deliveryDate: '2024-02-20',
    salesperson: '李四',
    createTime: '2024-01-16 14:20:00',
    remark: '标准订单'
  },
  {
    id: 3,
    orderNo: 'SO202401003',
    customerName: '深圳创新企业',
    customerContact: '王主管',
    totalAmount: 156000,
    status: 'producing',
    priority: 'urgent',
    deliveryDate: '2024-02-10',
    salesperson: '王五',
    createTime: '2024-01-17 11:15:00',
    remark: '加急订单，需要特殊处理'
  },
  {
    id: 4,
    orderNo: 'SO202401004',
    customerName: '广州制造公司',
    customerContact: '赵部长',
    totalAmount: 67000,
    status: 'ready',
    priority: 'low',
    deliveryDate: '2024-02-25',
    salesperson: '赵六',
    createTime: '2024-01-18 16:45:00',
    remark: '常规订单'
  },
  {
    id: 5,
    orderNo: 'SO202401005',
    customerName: '杭州电商平台',
    customerContact: '钱经理',
    totalAmount: 234000,
    status: 'shipped',
    priority: 'high',
    deliveryDate: '2024-02-12',
    salesperson: '钱七',
    createTime: '2024-01-19 10:30:00',
    remark: '大额订单，已发货'
  }
]

// 状态相关方法
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'info',
    producing: 'primary',
    ready: 'success',
    shipped: 'success',
    completed: '',
    cancelled: 'danger'
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已审核',
    producing: '生产中',
    ready: '待发货',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getPriorityType = (priority) => {
  const priorityMap = {
    low: 'info',
    medium: '',
    high: 'warning',
    urgent: 'danger'
  }
  return priorityMap[priority] || ''
}

const getPriorityText = (priority) => {
  const priorityMap = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return priorityMap[priority] || priority
}

// 事件处理方法
const handleAdd = () => {
  dialogTitle.value = '新增订单'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑订单'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  currentOrder.value = row
  viewDialogVisible.value = true
}

const handleCommand = async (command) => {
  const { action, row } = command
  
  try {
    switch (action) {
      case 'approve':
        await ElMessageBox.confirm('确认审核通过该订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'approved'
        ElMessage.success('订单审核通过')
        break
      case 'ship':
        await ElMessageBox.confirm('确认发货该订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'shipped'
        ElMessage.success('订单已发货')
        break
      case 'complete':
        await ElMessageBox.confirm('确认完成该订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'completed'
        ElMessage.success('订单已完成')
        break
      case 'cancel':
        await ElMessageBox.confirm('确认取消该订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'cancelled'
        ElMessage.success('订单已取消')
        break
    }
  } catch {
    // 用户取消操作
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerName: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (formData.id) {
      // 编辑
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        Object.assign(tableData.value[index], {
          ...formData,
          orderNo: tableData.value[index].orderNo,
          createTime: tableData.value[index].createTime
        })
      }
      ElMessage.success('订单更新成功')
    } else {
      // 新增
      const newOrder = {
        ...formData,
        id: Date.now(),
        orderNo: `SO${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(tableData.value.length + 1).padStart(3, '0')}`,
        status: 'pending',
        createTime: new Date().toLocaleString('zh-CN')
      }
      tableData.value.unshift(newOrder)
      pagination.total++
      ElMessage.success('订单创建成功')
    }
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    customerName: '',
    customerContact: '',
    deliveryDate: '',
    priority: 'medium',
    salesperson: '',
    totalAmount: 0,
    remark: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const loadData = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    let filteredData = [...mockData]
    
    // 应用搜索过滤
    if (searchForm.orderNo) {
      filteredData = filteredData.filter(item => 
        item.orderNo.toLowerCase().includes(searchForm.orderNo.toLowerCase())
      )
    }
    if (searchForm.customerName) {
      filteredData = filteredData.filter(item => 
        item.customerName.toLowerCase().includes(searchForm.customerName.toLowerCase())
      )
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    pagination.total = filteredData.length
    
    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    tableData.value = filteredData.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.sales-order-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.amount-text {
  color: #e6a23c;
  font-weight: bold;
}

.order-form .el-form-item {
  margin-bottom: 20px;
}

.order-detail {
  margin: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sales-order-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>